package ld.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import ld.mapper.BookMapper;
import ld.pojo.PageResult;
import ld.pojo.book;
import ld.service.BookService;
import ld.util.MyBatisUtil;
import ld.vo.BookVo;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * @Author: Liudao
 * @Date: 2022-07-27-15:55
 * @Description:
 */
public class BookServiceImpl implements BookService {
    private BookMapper bookMapper;
    public BookServiceImpl(){
        bookMapper = MyBatisUtil.getSqlSession().getMapper(BookMapper.class);
    }

    public List<book> findAll() {
        try(SqlSession sqlSession = MyBatisUtil.getSqlSession()){
            bookMapper = sqlSession.getMapper(BookMapper.class);
            List<book> books = bookMapper.findAll();
            MyBatisUtil.getSqlSession().close();
            return books;
        }

    }

    @Override
    public PageResult<book> findByPage(int page, int pagesize) {
        try(SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            //得到mapper
            bookMapper = sqlSession.getMapper(BookMapper.class);
            //开始分页
            PageHelper.startPage(page, pagesize);
            //得到所有学生
            List<book> books = bookMapper.findAll();
            //得到pageinfo对象
            PageInfo<book> bookPageInfo = new PageInfo<>(books);
            //返回
            return new PageResult<>(bookPageInfo.getTotal(), bookPageInfo.getList());

        }
    }

    @Override
    public PageResult<book> search(int page, int pagesize, BookVo bookVo) {
        //开始分页
        PageHelper.startPage(page, pagesize);
        try(SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            //得到mapper
            bookMapper = sqlSession.getMapper(BookMapper.class);
            //开始查询
            List<book> books = bookMapper.search(bookVo);
            //得到pageinfo对象
            PageInfo<book> bookPageInfo = new PageInfo<>(books);
            //返回
            return new PageResult<>(bookPageInfo.getTotal(),bookPageInfo.getList());

        }
    }

    @Override
    public boolean add(book book) {
        try(SqlSession session = MyBatisUtil.getSqlSession()){
            bookMapper = session.getMapper(BookMapper.class);
            return bookMapper.add(book);
        }
    }

    @Override
    public boolean delbk(int bookid) {
        try(SqlSession session = MyBatisUtil.getSqlSession()){
            bookMapper = session.getMapper(BookMapper.class);
            boolean delbk = bookMapper.delbk(bookid);
            return delbk;
        }
    }
}
